package com.it.system.interceptor;

import com.it.system.jwt.JwtUtil;
import com.it.system.jwt.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是前台的请求,直接放行
        if("front".equals(request.getHeader("requestType"))){
            return true;
        }

        //1.从请求头中获取token
        String token = request.getHeader("token");
        
        //2.校验令牌token
        if(token!=null){
            try {
                Payload payload = JwtUtil.parseJwtToken(token);
                return true; //校验通过异常,那就放行!!!
            } catch (Exception e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
                return false;
            }
        }
        
        //3.1.为null=没有登录或过期了
        //告诉浏览器我要给你响应一个json数据[自动将json格式的字符串-json对象],给前端的响应拦截器做处理
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
        return false;
    }
}